#!/usr/bin/env bash
set -euo pipefail

SCRIPT_NAME=$(basename "$0")
OUTPUT_FILE=".env"

echo "[INFO] ${SCRIPT_NAME} starting (non-interactive)" >&2

# Pre-flight checks
if ! command -v az >/dev/null 2>&1; then
  echo "[ERROR] Azure CLI (az) not found in PATH" >&2
  exit 4
fi

# Check login. If missing, automatically run device code login so user gets code.
if ! SUBSCRIPTION_ID=$(az account show --query id -o tsv 2>/dev/null); then
  echo "[INFO] No active Azure CLI session. Running 'az login --use-device-code'..." >&2
  if az login --use-device-code; then
    SUBSCRIPTION_ID=$(az account show --query id -o tsv)
  else
    echo "[ERROR] az login failed or was cancelled." >&2
    exit 4
  fi
fi

echo "[INFO] Subscription: ${SUBSCRIPTION_ID}" >&2

############# Auto-discovery #############
OVERRIDE_RG=${AZURE_RESOURCE_GROUP_NAME:-}
OVERRIDE_ACCOUNT=${AZURE_OPENAI_ACCOUNT_NAME:-}

mapfile -t CS_RESOURCES < <(az resource list --resource-type Microsoft.CognitiveServices/accounts \
  --query "[?kind=='AIServices'||kind=='OpenAI'].[resourceGroup,name]" -o tsv 2>/dev/null || true)

if [[ ${#CS_RESOURCES[@]} -eq 0 ]]; then
  echo "[ERROR] No AIServices/OpenAI accounts found in subscription." >&2
  exit 3
fi

if [[ -n "$OVERRIDE_RG" ]]; then
  RESOURCE_GROUP="$OVERRIDE_RG"
else
  RESOURCE_GROUP=$(printf '%s\n' "${CS_RESOURCES[@]}" | awk '{print $1}' | \
    awk '{count[$1]++} END {for (c in count) print count[c], c}' | sort -k1,1nr -k2,2 | head -1 | awk '{print $2}')
fi

if ! az group show -n "$RESOURCE_GROUP" >/dev/null 2>&1; then
  echo "[ERROR] Chosen resource group '$RESOURCE_GROUP' not found." >&2
  exit 2
fi

PROJECT_NAME="${RESOURCE_GROUP}-project"

if [[ -n "$OVERRIDE_ACCOUNT" ]]; then
  SELECTED_ACCOUNT="$OVERRIDE_ACCOUNT"
else
  mapfile -t ACCOUNT_NAMES < <(printf '%s\n' "${CS_RESOURCES[@]}" | awk -v rg="$RESOURCE_GROUP" '$1==rg {print $2}' | sort -u)
  if [[ ${#ACCOUNT_NAMES[@]} -eq 0 ]]; then
    echo "[ERROR] No accounts found in selected RG '$RESOURCE_GROUP'." >&2
    exit 3
  fi
  SELECTED_ACCOUNT=$(printf '%s\n' "${ACCOUNT_NAMES[@]}" | awk 'BEGIN{IGNORECASE=1} /openai/ {print; found=1} END{if(!found) exit 1}') || SELECTED_ACCOUNT="${ACCOUNT_NAMES[0]}"
fi

echo "[INFO] Selected Resource Group: ${RESOURCE_GROUP}" >&2
echo "[INFO] Selected Account:       ${SELECTED_ACCOUNT}" >&2

ENDPOINT="https://${SELECTED_ACCOUNT}.openai.azure.com/"

# Retrieve key (key1)
# If retrieval fails, we keep empty string.
OPENAI_KEY=""
if ! OPENAI_KEY=$(az cognitiveservices account keys list -n "$SELECTED_ACCOUNT" -g "$RESOURCE_GROUP" --query key1 -o tsv 2>/dev/null); then
  echo "[WARN] Unable to retrieve API key (insufficient role?). Leaving empty." >&2
fi

# Prepare env content
ENV_CONTENT=$(cat <<EOF
# Generated by ${SCRIPT_NAME} on $(date -u +%Y-%m-%dT%H:%M:%SZ)
AZURE_RESOURCE_GROUP_NAME="${RESOURCE_GROUP}"
AZURE_PROJECT_NAME="${PROJECT_NAME}"
AZURE_OPENAI_DEPLOYMENT_NAME="gpt-4o-mini"
AZURE_OPENAI_API_VERSION="2024-12-01-preview"
AZURE_SUBSCRIPTION_ID="${SUBSCRIPTION_ID}"
AZURE_OPENAI_ENDPOINT="${ENDPOINT}"
AZURE_OPENAI_API_KEY="${OPENAI_KEY}"
EOF
)

# Write file (always overwrite silently for unattended use)
if [[ -f "$OUTPUT_FILE" ]]; then
  echo "[INFO] Overwriting existing $OUTPUT_FILE" >&2
fi
echo "$ENV_CONTENT" > "$OUTPUT_FILE"

# Mask key for summary
MASKED_KEY="${OPENAI_KEY:0:4}****${OPENAI_KEY: -4}"
[[ -z "$OPENAI_KEY" ]] && MASKED_KEY="(empty)"

echo "[INFO] Wrote ${OUTPUT_FILE}" >&2
echo "[SUMMARY]" >&2
echo "  Resource Group:   ${RESOURCE_GROUP}" >&2
echo "  Project Name:     ${PROJECT_NAME}" >&2
echo "  Subscription ID:  ${SUBSCRIPTION_ID}" >&2
echo "  OpenAI Account:   ${SELECTED_ACCOUNT}" >&2
echo "  Endpoint:         ${ENDPOINT}" >&2
echo "  Key (masked):     ${MASKED_KEY}" >&2

exit 0
